package com.h5lib.xlsx4j;

import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class XLSXReader implements Closeable {


    private XLSXResource xlsxResource;
    private List<String> sharedStrings;

    public XLSXReader(InputStream input) {
        xlsxResource = new StreamXLSXResource(input);
    }
    
    public XLSXReader(XLSXResource resource) {
        xlsxResource = resource;
    }

    /**
     *
     * fixme
     *
     * @param i
     * @return
     * @throws IOException
     * @throws XmlPullParserException 
     * @throws XMLStreamException
     */
    public XMLSheetReader getSheet(int i) throws IOException, XmlPullParserException {

        String name = "xl/worksheets/sheet" + (i + 1) + ".xml";

        if( !xlsxResource.has(name) ) {
            throw new FileNotFoundException(name);
        }

        XMLSheetReader reader = getSheetReader(name);
        reader.setSharedStrings(getSharedStrings());

        return reader;
    }

    private XMLSharedStringReader getSharedStringsReader() throws IOException, XmlPullParserException {

        InputStream stream = xlsxResource.get("xl/sharedStrings.xml");
        XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser();
        newPullParser.setInput(stream, "UTF-8");
        XMLSharedStringReader reader = new XMLSharedStringReader(newPullParser);

        return reader;
    }

    private XMLSheetReader getSheetReader(String name) throws IOException, XmlPullParserException {

        InputStream stream = xlsxResource.get(name);
        XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser();
        newPullParser.setInput(stream, "UTF-8");
		XMLSheetReader reader = new XMLSheetReader(newPullParser);
        return reader;
    }

    private List<String> getSharedStrings() {
        if( sharedStrings == null ) {
        	try {
				sharedStrings = getSharedStringsReader().fetchAll();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

        }

        return sharedStrings;
    }

    public void setSharedStrings(List<String> sharedStrings) {
        this.sharedStrings = sharedStrings;
    }

    @Override
    public void close() throws IOException {
        xlsxResource.close();
    }
}
